package hp.netty.bean;

import hp.netty.Protocol;
import org.apache.log4j.Logger;

import java.nio.ByteBuffer;

/**
 * Created by 6v on 2019/5/5.
 */
public class EnvMonitorByteBean {

    private static Logger log = Logger.getLogger(EnvMonitorByteBean.class);

    private final byte[] head = {(byte) 0xfa, (byte) 0xf3};

    /**
     * 包头、包尾、数据长度 校验和均正确，说明是协议正确
     */
    public Boolean isLegal(byte[] pack) {
        if (pack.length == 63) {
            if (head[0] == pack[0] && head[1] == pack[1]) {
                byte[] checkArray = new byte[61];
                System.arraycopy(pack, 3, checkArray, 0, 31);
                byte[] checkSumArray = new byte[2];
                System.arraycopy(pack, 61, checkSumArray, 0, 2);
                if (checkSumArray == check(checkArray)) {
                    return true;
                } else {
                    log.info("校验和不一致");
                }
            } else {
                log.info("包头不一致");
            }
        } else {
            log.info("包长不等于63");
        }

        return false;
    }

    public static int getUnsignedByte(byte data) {      //将data字节型数据转换为0~255 (0xFF 即BYTE)。
         return data & 0x0FF;
    }


    public static void main(String[] args) {
        System.out.println(getUnsignedByte((byte) 0xfa ));
        byte[] b = {(byte) 0xfa, (byte) 0xf3};
        System.out.println(new Protocol().getUnsignedByte(new Protocol().bytesToShort(b)));
        byte[] c = {07,46,07,30,50,72,67,00};
        StringBuffer sb = new StringBuffer();
        for(int j=0;j<c.length;j++){
            if(c[j]>9){
                sb.append(c[j]);
            }else{
                sb.append("0"+c[j]);
            }

        }
        System.out.println(Long.parseLong(sb+""));
    }


    public static byte[] check(byte[] pack) {
        int sum = 0;
        for (int i = 0; i < pack.length; i++) {
            sum += pack[i];
        }
        ByteBuffer buffer = ByteBuffer.allocate(4);
        int low = sum & 0xffff;
        buffer.putInt(0, low);
        return buffer.array();
    }


}
